<template>
  <div class="image-upload">
    <el-upload
      v-show="!isShowProgress"
      class="avatar-uploader"
      action="#"
      :http-request="onRequest"
      :file-list="fileList"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :before-upload="beforeAvatarUpload"
      :limit="limit"
      :on-exceed="onExceed"
      list-type="picture-card"
      accept="image/jpeg,image/png"
    >
      <span>上传图片</span>
      <i class="el-icon-circle-close avatar-uploader-icon"></i>
    </el-upload>
    <!-- 进度条 -->
    <el-progress v-if="isShowProgress" type="circle" :percentage="percentage" />
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="imgUrl">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDZw3uUnvnOilW1EApEkzxd3C4ey1nJhoe',
  SecretKey: 'bvymKbcMp0vZw2rQknZ6NM4WhaCYeT1I'
})
export default {
  name: 'UpdateImage',
  props: {
    limit: {
      type: Number,
      default: _ => 0
    }
  },
  data () {
    return {
      fileList: [
      ],
      dialogVisible: false,
      imgUrl: '',
      percentage: 0,
      isShowProgress: false
    }
  },

  created () {
  },

  methods: {
    // 发送请求
    onRequest (data) {
      this.isShowProgress = true
      this.timerId = setInterval(() => {
        if (this.percentage < 99) {
          this.percentage++
        } else {
          clearInterval(this.timerId)
        }
      }, 500)
      cos.putObject({
        Bucket: 'hrsaas24-1308960756', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-shanghai', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: data.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        onProgress: progressData => {
          if (progressData.percent === 1) {
            this.percentage = 100
            clearInterval(this.timerId)
            setTimeout(() => {
              this.isShowProgress = false
            }, 500)
          }
        }
      }, (err, data) => {
        if (!err && data.statusCode === 200) {
          if (err) {
            this.isShowProgress = false
            this.$message.error('网络错误,上传失败')
            this.fileList.splice(this.fileList.length - 1, 1)
          }
          const lastIndex = this.fileList.length - 1
          this.fileList[lastIndex].url = 'http://' + data.Location
          this.$message.success('图片上传成功!')
          this.$emit('on-success', this.fileList)
        }
      })
    },
    // 预览
    handlePreview (file) {
      this.imgUrl = file.url
      this.dialogVisible = true
    },
    // 删除
    handleRemove (file, fileList) {
      this.fileList = fileList
      this.$emit('on-delete')
    },
    // 图片上传之前
    beforeAvatarUpload (file) {
      const maxSize = 1 * 1024 * 1024
      const imageType = ['image/jpeg', 'image/png']
      if (!imageType.includes(file.type)) {
        this.$message.error('请上传正确的图片格式!')
        return false
      }
      if (file.size > maxSize) {
        this.$message.error('请上传1Mb以内的图片哦!')
        return false
      }
    },
    // 文件状态改变
    handleChange (file, fileList) {
      this.fileList = fileList
    },
    onExceed () {
      this.$message.error('最多只能上传' + this.limit + '张图片')
    }
  }
}
</script>

<style lang='less' scoped>
.image-upload {
  position: relative;
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    position: absolute;
    right: 0;
    top: 0;
    -webkit-transform: translate(50%,-50%);
    transform: translate(50%,-50%);
    background: #fff;
    font-size: 18px;
    color: #999;
}
}
</style>
